<?php

namespace App\Http\Controllers\Front;

use App\Interfaces\UserViewHistoryService;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Interfaces\GoodsService;
use App\Interfaces\PictureService;
use App\Interfaces\BrandService;
use App\Interfaces\CategoryService;
use App\Models\Goods;
use App\Models\Order;
use App\Models\OrderGoods;
use App\Models\Category;
use App\Interfaces\CommentService;
use Auth,Session,Log;
use App\Models\ProductSku;

class GoodsController extends Controller
{
    /**
     * 商品详情页
     *
     * @return \Illuminate\Http\Response
     */
    public function show($goods_id, GoodsService $goodsService, PictureService $pictureService, BrandService $brandService,UserViewHistoryService $userViewHistoryService,Request $request)
    {
		$proview = '';
		if($request->proview){
			$proview = $request->proview;
		}

    	$goods = $goodsService->get($goods_id);
        //$condition="allComment";
        $condition=$request->has('condition')?$request->get('condition'): "allComment";

    	if($goods){
			$is_on_sale = $goods->is_on_sale;
			/*if($is_on_sale==2){
				return view('errors.503');
			}*/

    		$goods_thumb = $goods->goods_thumb;
    		$brand_id = $goods->brand_id;

    		//获取品牌信息
    		$brandObj = $brandService->get($brand_id);
    		$goods['brandArr'] = $brandObj;

    		//获取商品图片数组
    		$pictureObj = $goodsService->getGoodsGallery($goods_id);
    		$goods['pictureArr'] = $pictureObj;

    	}//end if()

		//浏览记录
		$userViewHistoryService->add($goods_id);

		$user=Auth::user();

        // return view('front.goods.detail', compact('goods', 'is_on_sale','orderGoods','goods_id','condition','user', 'proview'));
        return view('front.goods.detail', compact('goods', 'is_on_sale', 'goods_id', 'condition', 'user', 'proview'));
    }


	/**
	 * 根据商品id获取商品的同类产品
	 * @param $goods_id
	 * @return mixed
	 */
	public function getSimilar($goods_id, CategoryService $categoryService){

		$goods = Goods::find($goods_id);
		$goods_name = $goods->goods_name;
		$cat_id = $goods->cat_id;

		$categoryGoods = Goods::where('cat_id', $cat_id)->where('is_on_sale', 1)->where('goods_id', '<>', $goods_id)->orderBy('add_time', 'desc')->get();

		$similarGoodsNum = $categoryGoods->count();
		if($similarGoodsNum<4){
			//TODO如果数量不够查找根分类下的商品
			$root_cat_obj = Category::where('parent_id',0)->orderBy('sort_order','desc')->orderBy('cat_id','asc')->get();
			foreach($root_cat_obj as $key=>$value){

			}//end foreach()
			//dd($root_cat_obj->toArray());
			foreach($root_cat_obj as $key=>$value){

				$root_cat_id = $value->cat_id;
				//echo "<BR>root_cat_id:".$root_cat_id;

				$categoryRootGoods = Goods::where('cat_id', $root_cat_id)->where('is_on_sale', 1)->where('goods_id', '<>', $goods_id)->orderBy('add_time', 'desc')->get();

			}//end foreach()

		}//end if()

		return $categoryGoods;
	}//end func getSimilar


	public function comment(Request $request,CommentService $commentService,PictureService $pictureService){

		$goods_id = $request->get('goods_id');
		$condition = $request->has('condition')?$request->get('condition'):"allcomment";
        $page = $request->get('page');

		$comments=$commentService->getComment($goods_id,$condition,$page);

		if(empty($comments)){
			return Response()->json(['message'=>'暂无评价','status'=>'0']);
		}
        $commentArr=$comments->toArray();

        foreach ($commentArr['data'] as $item=>$comment) {
            $picArr=explode(',',$comment['picture']);
            $arr=[];
            foreach ($picArr as $key=>$pic) {
                $arr[$key]=[$pictureService::thumb($pic, 70, 70),$pictureService::thumb($pic, 400, 400)];
            }
            $commentArr['data'][$item]['picture']=$arr;
        }

		return Response()->json(['comments'=>$commentArr,'status'=>'1']);

	}

	/*
	 * 订单商品快照
	 */
	public function goodsArchive($order_sn, $goods_id){

		$order_id = Order::where('order_sn', $order_sn)->pluck('order_id');
		//$goods_id = Goods::where('goods_sn', $goods_sn)->pluck('goods_id');

		$order_goods = OrderGoods::where('order_id', $order_id)->where('goods_id', $goods_id)->first();

		$user_id = Auth::user()->id;

		//还差页面
		return view('front.goods.archive', compact('order_goods', 'user_id'));
	}//end func tradeArchive()

	/**
	 * [根据所选商品属性跳转到相应的商品，同一个产品下的商品]
	 * @param  [type] $goods_id         [商品id]
	 * @param  [type] $attributValueArr [商品属性数组]
	 * @return [type]                   [description]
	 */
	public function attributValueRedirect($goods_id, Request $request)
	{

        $return = ['status'=>0, 'message'=>'', 'data'=>''];

		$attributValueArr = $request->attributValueArr;		//如：[5,8,9]
		$skus = $this->getSkus($attributValueArr,$delimiter=',');

		$product_id = ProductSku::where('goods_id', $goods_id)->pluck('product_id');

		$productSkus = ProductSku::where('product_id', $product_id)->get();
		if ($productSkus) {
			foreach ($productSkus as $key => $productSku) {
				$attribute_group = $productSku->attribute_group;

				if(in_array($attribute_group, $skus)){
					$goods_id = $productSku->goods_id;
					break;
				}else{
					continue;
				}
			}//end if()
		}//end if()

		$url = 'goods/'.$goods_id;
		if ($request->ajax()) {
		    $return['status'] = 1;
		    $return['data'] = $url;

		    return $return;
		}else{
			return Redirect($url);
		}//end if()


	}//end func attributValueRedirect

	/**
	 * 根据属性数组找到所有的属性组合
	 * @param  [type] $arr       [description]
	 * @param  string $delimiter [description]
	 * @return [type]            [description]
	 */
    function getSkus($arr,$delimiter=','){

        //sku数组
        $skus = [];
        //正向排列
        sort( $arr );
        //获取数组长度
        $len = count ( $arr )-1;
        //记录传入的排列
        $skus[]=implode($delimiter,$arr);
        while (true){
            //从右侧开始找到第一个左侧(A)<右侧(B)的数字序列
            for ( $i = $len ; $i >=0; $i --){
                if ( $arr [ $i ]> @$arr[$i -1]){
                    $here = $i -1;
                    break ;
                }
            }
            //若找到了则开始换位
            if ( $here >=0){
                //从有右向左侧找，第一个比左侧(A)大的数字(C)交换位置得到CBA
                for ( $j = $len ; $j > $here ; $j --){
                    if ( $arr [ $here ]< $arr [ $j ]){
                        $revers = $j ;
                        list( $arr [ $here ], $arr [ $j ]) = array ( $arr [ $j ], $arr [ $here ]);
                        break ;
                    }
                }
                //将后续数字倒序得到CAB
                unset( $newarr );
                for ( $h = $here +1; $h <= $len ; $h ++){
                    $newarr [] = $arr [ $h ];
                    unset( $arr [ $h ]);
                }

                $arr = array_merge ( $arr , array_reverse ( $newarr ,TRUE));
                $skus[]=implode($delimiter,$arr);

            } else {
                break ;
            }
        }
        return $skus ;

    }//end func getSkus
}//end class 
